import tkinter as tk  
from tkinter import messagebox  
from tkinterdnd2 import DND_FILES, TkinterDnD  
import imageio  
import os  

class VideoToGifConverter:  
    def __init__(self):  
        self.root = TkinterDnD.Tk()  
        self.root.title("视频转 GIF 工具")  
        self.root.geometry("400x200")  

        self.label = tk.Label(self.root, text="将视频拖放到此处")  
        self.label.pack(pady=20)  

        # Bind the drop event  
        self.root.drop_target_register(DND_FILES)  
        self.root.dnd_bind('<<Drop>>', self.handle_drop)  

        self.video_path = None  

    def handle_drop(self, event):  
        # Get the video path from the drop event  
        files = self.root.tk.splitlist(event.data)  
        if files:  
            self.video_path = files[0]  
            self.convert_video()  

    def convert_video(self):  
        if self.video_path and os.path.isfile(self.video_path):  
            output_path = os.path.join(os.path.dirname(self.video_path),  
                                        os.path.splitext(os.path.basename(self.video_path))[0] + '.gif')  
            try:  
                video = imageio.get_reader(self.video_path)  
                fps = video.get_meta_data()['fps']  
                with imageio.get_writer(output_path, mode='I', fps=fps) as writer:  
                    for frame in video:  
                        writer.append_data(frame)  
                messagebox.showinfo("转换完成", f"视频已成功转换为 GIF 并保存至：\n{output_path}")  
            except Exception as e:  
                messagebox.showerror("错误", f"转换过程中出现错误：\n{str(e)}")  
        else:  
            messagebox.showwarning("警告", "请拖放有效的视频文件")  

    def on_close(self):  
        self.root.destroy()  

if __name__ == "__main__":  
    converter = VideoToGifConverter()  
    converter.root.mainloop()




